package com.cdtu;

import com.cdtu.utils.FileUtils;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author Mika
 * @date 2025/03/01 18:50
 **/
@Slf4j
public class TCPServer {
    public static String HOST;
    public static int PORT;

    static {
        HOST = FileUtils.getProp("hostIpAddr");
        PORT = Integer.parseInt(FileUtils.getProp("port"));
    }

    public static void startServer() {
        // 异步启动
        Thread thread = new Thread(TCPServer::run);
        thread.start();
    }

    public static void run() {
        // 创建ServerSocket，指定监听的端口
        try (ServerSocket serverSocket = new ServerSocket()) {

            serverSocket.bind(new InetSocketAddress(HOST, PORT));
            log.info("Listening for incoming connections..." + " IP:" + HOST + " +++ " + "port:" + PORT);
            while (true) {
                // 接收客户端的连接请求
                Socket socket = serverSocket.accept();

                // 创建一个新线程处理每个 socket 连接
                Thread thread = new Thread(() -> {
                    // 获取输入流，读取客户端发送的数据
                    try (InputStream inputStream = socket.getInputStream()) {

                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        StringBuilder stringBuilder = new StringBuilder();

                        while ((bytesRead = inputStream.read(buffer)) != -1) {
                            stringBuilder.append(new String(buffer, 0, bytesRead));
                        }

                        String data = stringBuilder.toString();
                        log.info("TCP 收到超脑服务器的报文: {}", data);
                        MessageController.txtScan(MessageController.xmlToJSON3(data));
                        socket.close();
                    } catch (IOException ignored) {
                        InetSocketAddress inetSocketAddress = (InetSocketAddress) socket.getRemoteSocketAddress();
                        log.warn("断开连接: {}:{}", inetSocketAddress.getHostName(), inetSocketAddress.getPort());
                    }
                });
                thread.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
